<template>
  <div class="login-container">
    <van-nav-bar title="登录">
      <template #left>
        <img class="logo" src="@/assets/images/logo.png" />
      </template>
    </van-nav-bar>
    <van-form @submit="onSubmit">
      <van-field
        v-model="formLogin.mobile"
        type="tel"
        label="手机号"
        placeholder="请输入手机号"
        required
        :rules="rules.tel"
      />
      <van-field
        v-model="formLogin.code"
        type="password"
        label="密码"
        placeholder="请输入密码"
        required
        :rules="rules.pwd"
      />
      <div style="margin: 16px;">
        <van-button block :loading='boolk' type="info" native-type="submit" loading-text="加载中..." >登录</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { loginAPI } from '../../api/user'
import { Notify } from 'vant'
import { mapMutations } from 'vuex'
export default {
  name: 'Login',
  data () {
    return {
      formLogin: {
        mobile: '13888888888',
        code: '246810' // 默认只能用246810后台规定了
      },
      rules: {
        tel: [
          {
            required: true,
            message: '请填写手机号',
            trigger: 'onChange'
          },
          {
            message: '请填写手机号',
            trigger: 'onChange',
            pattern: /^1[3456789]\d{9}$/
          }
        ],
        pwd: [
          {
            required: true,
            message: '请填写密码',
            trigger: 'onChange'
          },
          {
            message: '请填写密码',
            trigger: 'onChange',
            pattern: /^\d{6}$/
          }

        ]
      },
      boolk: false
    }
  },
  methods: {
    ...mapMutations(['setToken', 'setRefreshToken']),
    async onSubmit () {
      try {
        this.boolk = true
        const resp = await loginAPI(this.formLogin)
        const { refresh_token: refreshToken, token } = resp.data
        this.setToken(token)
        localStorage.setItem('token', token)
        this.setRefreshToken(refreshToken)
        localStorage.setItem('refresh_token', refreshToken)
        Notify({ type: 'success', message: '登录成功' })
        console.log(resp)
        this.$router.replace({
          path: '/layout'
        })
      } catch (e) {
        Notify({ type: 'warning', message: '账号密码错误' })
      } finally {
        this.boolk = false
      }
    }
  }
}
</script>

<style lang="less" scoped>
.logo {
  width: 100px;
  height: 30px;
}

/* /deep/ 就是把data-v-hash值选择器写到类名的前面 */
</style>
